package com.h.files.selector.activity.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public final class StringUtils {

	private final static Pattern emailer = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
	private final static Pattern phone = Pattern.compile("1[3\\d|4[5|7]|5[0|1|5-9]|7[0|6|7|8]|8\\d]|\\d{8}");
	private final static SimpleDateFormat datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private final static SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");

	private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
	private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
	private static final String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
	private final static String regxpForHtml = "<([^>]*)>"; // 过滤所有以<开头以>结尾的标签

	private final static Pattern URL = Pattern.compile("^(https|http)://.*?$(net|com|.com.cn|org|me|info|top|cn|cc|tv|)");

	StringUtils() {
	}

	public static boolean isNullOrEmpty(Object value) {
		if (null == value)
			return true;
		return "".equals(value.toString());
	}

	public static boolean isPhone(Object value) {
		if (isNullOrEmpty(value))
			return false;
		return phone.matcher(value.toString()).matches();
	}

	public static boolean isUrl(String str) {
		if (str == null || str.trim().length() == 0)
			return false;
		return URL.matcher(str).matches();
	}

	public static boolean isEmail(Object email) {
		if (isNullOrEmpty(email))
			return false;
		return emailer.matcher(email.toString()).matches();
	}

	public static boolean isJSONString(String string) {
		if (isNullOrEmpty(string))
			return false;
		try {
			new JSONObject(string);
		} catch (Exception e) {
			try {
				new JSONArray(string);
			} catch (JSONException e1) {
				e1.printStackTrace();
				return false;
			}
		}
		return true;
	}

	public static long random(int min, int max) {
		return Math.round(Math.random() * (max - min) + min);
	}

	public static String md5(String code, int length) {
		String md5 = "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(code.getBytes());
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			if (16 == length)
				md5 = buf.toString().substring(8, 24);
			else
				md5 = buf.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return md5;
	}

	public static String decode(String value, String charsetName) {
		try {
			return URLDecoder.decode(value, charsetName);
		} catch (UnsupportedEncodingException e) {
			LogUtils.e("解码失败：" + value + "。charsetName=" + charsetName, e);
			return value;
		}
	}

	public static String encode(String value, String charsetName) {
		try {
			return URLEncoder.encode(value, charsetName);
		} catch (UnsupportedEncodingException e) {
			LogUtils.e("编码失败：" + value + "。charsetName=" + charsetName, e);
			return value;
		}
	}

	public static String encode(String value) {
		return encode(value, "UTF-8");
	}

	public static String getString(InputStream is) {
		StringBuffer res = new StringBuffer();
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader read = new BufferedReader(isr);
		try {
			String line;
			while (null != (line = read.readLine())) {
				res.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != isr) {
				try {
					isr.close();
					isr = null;
				} catch (IOException e) {
				}
			}
			if (null != read) {
				try {
					read.close();
					read = null;
				} catch (IOException e) {
				}
			}
			if (null != is) {
				try {
					is.close();
					is = null;
				} catch (IOException e) {
				}
			}
		}
		return res.toString();
	}

	public static String createSinaShortUrl(String url) {
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet("http://api.t.sina.com.cn/short_url/shorten.json?source=3271760578&url_long=" + url);
		get.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		get.setHeader("Accept-Encoding", "gzip, deflate");
		get.setHeader("Accept-Language", "zh-HK,zh-CN;q=0.8,zh;q=0.6,en-US;q=0.4,en;q=0.2");
		get.setHeader("Cache-Control", "no-cache");
		get.setHeader("DNT", "1");
		get.setHeader("Host", "api.t.sina.com.cn");
		get.setHeader("Pragma", "no-cache");
		get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0");
		String result = url;
		try {
			HttpResponse resp = client.execute(get);
			result = getString(resp.getEntity().getContent());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return url;
	}

	public static String getDateTimeNow(String format) {
		return new SimpleDateFormat(format).format(new Date());
	}

	public static String friendly_time(String dateStr, int day) {
		if (1 > day)
			day = 1;
		Date time = toDate(dateStr);
		if (time == null) {
			return "Unknown";
		}
		String ftime = "";
		Calendar cal = Calendar.getInstance();
		long lt = time.getTime() / 86400000;
		long ct = cal.getTimeInMillis() / 86400000;
		int days = (int) (ct - lt);
		if (days == 0) {
			int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
			if (hour == 0)
				ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
			else
				ftime = hour + "小时前";
		} else if (days == 1 && 1 <= day) {
			ftime = "昨天";
		} else if (days == 2 && 2 <= day) {
			ftime = "前天";
		} else if (days > 2 && days <= day) {
			ftime = days + "天前";
		} else if (days > day) {
			ftime = date.format(time);
		}
		return ftime;
	}

	public static int getMonthLastDay(int year, int month) {
		Calendar a = Calendar.getInstance();
		a.set(Calendar.YEAR, year);
		a.set(Calendar.MONTH, month);
		a.set(Calendar.DATE, 1);// 把日期设置为当月第一天
		a.roll(Calendar.DATE, -1);// 日期回滚一天，也就是最后一天
		int maxDate = a.get(Calendar.DATE);
		return maxDate;
	}

	/**
	 * 以友好的方式显示时间
	 * 
	 * @param sdate
	 * @return
	 */
	public static String friendly_time(String sdate) {
		return friendly_time(sdate, 5);
	}

	public static Date toDate(String dateStr) {
		try {
			return datetime.parse(dateStr);
		} catch (ParseException e) {
			try {
				return date.parse(dateStr);
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
		}
		return null;
	}

	public static String delHTMLTag(String htmlStr) {
		Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
		Matcher m_script = p_script.matcher(htmlStr);
		htmlStr = m_script.replaceAll(""); // 过滤script标签

		Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
		Matcher m_style = p_style.matcher(htmlStr);
		htmlStr = m_style.replaceAll(""); // 过滤style标签

		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(htmlStr);
		htmlStr = m_html.replaceAll(""); // 过滤html标签

		return htmlStr.trim(); // 返回文本字符串
	}

	/**
	 * 基本功能：替换标记以正常显示
	 * 
	 * @param input
	 * @return String
	 */
	public static String replaceTag(String input) {
		if (!hasSpecialChars(input)) {
			return input;
		}
		StringBuffer filtered = new StringBuffer(input.length());
		char c;
		for (int i = 0; i <= input.length() - 1; i++) {
			c = input.charAt(i);
			switch (c) {
			case '<':
				filtered.append("&lt;");
				break;
			case '>':
				filtered.append("&gt;");
				break;
			case '"':
				filtered.append("&quot;");
				break;
			case '&':
				filtered.append("&amp;");
				break;
			default:
				filtered.append(c);
			}

		}
		return (filtered.toString());
	}

	/**
	 * 基本功能：判断标记是否存在
	 * 
	 * @param input
	 * @return boolean
	 */
	public static boolean hasSpecialChars(String input) {
		boolean flag = false;
		if ((input != null) && (input.length() > 0)) {
			char c;
			for (int i = 0; i <= input.length() - 1; i++) {
				c = input.charAt(i);
				switch (c) {
				case '>':
					flag = true;
					break;
				case '<':
					flag = true;
					break;
				case '"':
					flag = true;
					break;
				case '&':
					flag = true;
					break;
				}
			}
		}
		return flag;
	}

	/**
	 * 基本功能：过滤所有以"<"开头以">"结尾的标签
	 * 
	 * @param str
	 * @return String
	 */
	public static String filterHtml(String str) {
		Pattern pattern = Pattern.compile(regxpForHtml);
		Matcher matcher = pattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		boolean result1 = matcher.find();
		while (result1) {
			matcher.appendReplacement(sb, "");
			result1 = matcher.find();
		}
		matcher.appendTail(sb);
		return sb.toString();
	}

	/**
	 * 基本功能：过滤指定标签
	 * 
	 * @param str
	 * @param tag
	 *            指定标签
	 * @return String
	 */
	public static String fiterHtmlTag(String str, String tag) {
		String regxp = "<\\s*" + tag + "\\s+([^>]*)\\s*>";
		Pattern pattern = Pattern.compile(regxp);
		Matcher matcher = pattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		boolean result1 = matcher.find();
		while (result1) {
			matcher.appendReplacement(sb, "");
			result1 = matcher.find();
		}
		matcher.appendTail(sb);
		return sb.toString();
	}

	/**
	 * 基本功能：替换指定的标签
	 * 
	 * @param str
	 * @param beforeTag
	 *            要替换的标签
	 * @param tagAttrib
	 *            要替换的标签属性值
	 * @param startTag
	 *            新标签开始标记
	 * @param endTag
	 *            新标签结束标记
	 * @return String
	 * @如：替换img标签的src属性值为[img]属性值[/img]
	 */
	public static String replaceHtmlTag(String str, String beforeTag, String tagAttrib, String startTag, String endTag) {
		String regxpForTag = "<\\s*" + beforeTag + "\\s+([^>]*)\\s*>";
		String regxpForTagAttrib = tagAttrib + "=\"([^\"]+)\"";
		Pattern patternForTag = Pattern.compile(regxpForTag);
		Pattern patternForAttrib = Pattern.compile(regxpForTagAttrib);
		Matcher matcherForTag = patternForTag.matcher(str);
		StringBuffer sb = new StringBuffer();
		boolean result = matcherForTag.find();
		while (result) {
			StringBuffer sbreplace = new StringBuffer();
			Matcher matcherForAttrib = patternForAttrib.matcher(matcherForTag.group(1));
			if (matcherForAttrib.find()) {
				matcherForAttrib.appendReplacement(sbreplace, startTag + matcherForAttrib.group(1) + endTag);
			}
			matcherForTag.appendReplacement(sb, sbreplace.toString());
			result = matcherForTag.find();
		}
		matcherForTag.appendTail(sb);
		return sb.toString();
	}
}
